/**
*@Author: QWP
*@Description: 审核相关功能
*@Date 2024-08-29 13:33
*/

import { AuditParams } from './../common/model/auditParams';
import { h } from 'vue';
import * as auditApi from '@/service/audit'
import { alertC, messageC, nullC } from '../util/common'
import AuditBack from '@/components/common/audit/AuditBack.vue'
import Audit from '@/components/common/audit/Audit.vue'
import AuditReportSel from '@/components/common/audit/AuditReportSel.vue'
import { Modal } from 'ant-design-vue'
import { cloneDeep } from 'lodash';

interface ReportParams {
  businessKey?: string, // 数据id
  billmajortype: string, // 模块类型
  billtype: string, // 单据类型
  processInstanceId: string, // 流程实例id  processintsid
  fkdycform: string, // 动态表单id
  msg?: string, // 审核，审核通过信息
  return_msg?: string, // 退回信息
}

export interface IAuditParams {
  type: string, // 业务类型，自定义的
  selDatas: any[], // 要操作的业务数据
  params?: ReportParams, // 额外的审核参数
  isDialog?: boolean, // 审核通过的时候判断是否需要弹窗输入意见，默认为true
  confirm?: boolean, // 是否需要确认
  fkdycform?: string | number, // 动态业务提交审核的表单id
}

// 上报、提交审核
export const useReport = async (param: IAuditParams) => {
  const { type = '', selDatas = [], params = {}, fkdycform = '' } = param
  if(selDatas.length == 0) {
    messageC("请先选择需要上报的数据!", "warning");
    return
  }

  if(selDatas.length != 1) {
    messageC("只能选择一条数据进行上报！", "warning");
    return
  }
  if(param.confirm != false) {
    try {
      await alertC("确认上报?", 'confirm')
    } catch (error) {
      return null
    }
  }
  const configParams = AuditParams[type] || {}
  const reportParams = { 
    ...configParams, 
    ...params, 
    fkdycform, 
    businessKey: selDatas[0]['keyid'],
    processInstanceId: selDatas[0]['processintsid']
  }

  // 上报保存
  const submit = async (value: object) => {
    const res = await auditApi.startProcess(value)
    messageC(res.msg, res.error == 200 ? "success" : "error")
    return res;
  }

  try {
    const res1 = await auditApi.getNextInfo(reportParams)
    if(res1.error == 200 && (res1.result || []).length > 0) {
      return new Promise((resolve, reject) => {
        const modal = Modal.confirm();
        let isLoading = false;
        modal.update({ title: '审核节点', icon: h(''),
          content: h(AuditReportSel, {
            selData: res1.result,
            isLoading: isLoading,
            onClose: () => {
              modal.destroy()
              reject()
            },
            onSubmit: async (value: any) => {
              isLoading = true;
              const res = await submit({ ...reportParams, ...formatMutilForm(value['nodeKey'], value) })
              if(res.error == 200) {
                setTimeout(() => {
                  modal.destroy()
                  isLoading = false;
                }, 500)
              }
              resolve(res)
            }
          }),
          footer: h(''),
          width: '600px',
          class: 'u-audit-back-dialog',
        });
      })
    }
    else {
      return submit(reportParams)
    }
  } catch (error) {}
}

// 取回
export const useRetrieve = async (param: IAuditParams) => {
  const { type = '', selDatas = [], params = {} } = param
  if(selDatas.length == 0) {
    messageC("请先选择需要取回的数据!", "warning");
    return
  }

  if(selDatas.length != 1) {
    messageC("只能选择一条数据进行取回！", "warning");
    return
  }

  // 审核完成
  if(selDatas[0]['status'] == 3) {
    messageC("该数据已审核完成，不能取回！", "warning");
    return
  }

  if(!selDatas[0]['processintsid']) {
    messageC("选中数据无流程实例ID，无法取回!", "warning");
    return
  }

  if(param.confirm != false) {
    try {
      await alertC("确认取回?", 'confirm')
    } catch (error) {
      return null
    }
  }
  const configParams = AuditParams[type] || {}
  const res = await auditApi.getBack({ 
    ...configParams, 
    ...params, 
    businessKey: selDatas[0]['keyid'], 
    proc_inst_id: selDatas[0]['processintsid'] 
  })
  try {
    messageC(res.msg, res.error == 200 ? "success" : "error")
  } catch (error) {}
  return res
}

// 同意审核
export const useSendWork = async (param: IAuditParams, formRef) => {
  const { type = '', selDatas = [], params = {}, isDialog = true } = param
  if(selDatas.length == 0) {
    messageC("请先选择需要审核的数据!", "warning");
    return
  }

  if(selDatas.length != 1) {
    messageC("只能选择一条数据进行审核！", "warning");
    return
  }

  if(selDatas[0]['status'] == 3) {
    messageC("流程已完成,无需操作！", "warning");
    return
  }

  const configParams = AuditParams[type] || {}
  const auditParams = { ...configParams, ...params, businessKey: selDatas[0]['keyid'], processInstanceId: selDatas[0]['processintsid'] }

  const submit = async (value?: object) => {
    try {
      await alertC("确认通过?", 'confirm')
    } catch (error) {
      return null
    }
    
    let res = null;
    try {
      res = await auditApi.sendWork({...auditParams, ...(value || {}) })
      messageC(res.msg, res.error == 200 ? "success" : "error")
      if(res.err == 200 && formRef) {
        try {
          formRef.value.formRef.form.resetFields()
        } catch (error) {}
      }
    } catch (error) {}
    return res
  }

  // 直接弹窗审核
  if(isDialog == true) {
    let isSelRes: any = {};
    try {
      isSelRes = await auditApi.getNextInfo(auditParams)
      return new Promise(async (resolve, reject) => {
        // if(isSelRes['error'] == 200 && isSelRes['result']) {
        const modal = Modal.confirm();
        modal.update({ title: '审核', icon: h(''),
          content: h(Audit, {
            selData: isSelRes['result'] || [],
            onClose: () => {
              modal.destroy()
              reject()
            },
            onSubmit: async (value: any) => {
              const res = await submit({ ...value, ...formatMutilForm(value['nodeKey'], value) })
              if(res.error == 200) {
                setTimeout(() => modal.destroy(), 500)
              }
              resolve(res)
            }
          }),
          footer: h(''),
          width: '600px',
          class: 'u-audit-back-dialog',
        });
        // }
        // else {
        //   const res = await submit()
        //   resolve(res)
        // }
      })
    } catch (error) { }
  }
  else {
    if(formRef) {
      try {
        await formRef.value.formRef.form.validate()
      } catch (error) {
        formRef.value.currntFlowTab()
        messageC("请先将审核信息填写完毕!");
        return
      }
    } else {
      messageC("请先将审核信息填写完毕!");
      return
    }

    let tForm = cloneDeep(formRef.value.form || {})

    return await submit({ ...tForm, ...formatMutilForm(tForm['nodeKey'], tForm) })
  }
}

// 退回
export const useReturnWork = async (param: IAuditParams, formRef) => {
  const { type = '', selDatas = [], params = {}, isDialog = true  } = param
  if(selDatas.length == 0) {
    messageC("请先选择需要退回的数据!", "warning");
    return
  }

  if(selDatas.length != 1) {
    messageC("只能选择一条数据进行退回！", "warning");
    return
  }

  // 审核完成
  if(selDatas[0]['status'] == 3) {
    messageC("该数据已审核完成，不能退回！", "warning");
    return
  }

  const configParams = AuditParams[type] || {}
  const submit = async (value: object) => {
    try {
      await alertC("确认退回?", 'confirm')
    } catch (error) {
      return null      
    }
    const res = await auditApi.returnWork({ ...configParams, ...params, ...value, businessKey: selDatas[0]['keyid'] })
    try {
      messageC(res.msg, res.error == 200 ? "success" : "error")
    } catch (error) {}

    return res
  }

  // 在流程查看页签中填写的审核信息
  let flowTabForm = {}
  if(formRef) {
    flowTabForm = formRef.value.form
  }
  return new Promise((resolve, reject) => {
    // 选择退回节点
    const modal = Modal.confirm();
    modal.update({
      title: '退回',
      icon: h(''),
      content: h(AuditBack, {
        params: { 
          ...{ ...params, ...configParams }, 
          businessKey: selDatas[0]['keyid'] 
        },
        returnMsg: nullC(flowTabForm['msg']),
        isHooks: true,
        onClose: () => {
          modal.destroy()
          reject()
        },
        onSubmit: async (value) => {
          const res = await submit(value)
          if(res.error == 200) {
            setTimeout(() => modal.destroy(), 500)
          }
          resolve(res)
        }
      }),
      footer: h(''),
      width: '600px',
      class: 'u-audit-back-dialog',
    });
  })
}

// 审核相关  1 上报、 2 审核、 3 退回   4 取回
export const useAuditAbout = async (type: string, auditParams: IAuditParams, formRef: any) => {
  try {
    // 上报
    if(type == '1') {
      return await useReport(auditParams)
    }
    // 审核
    else if(type == '2') {
      return await useSendWork(auditParams, formRef)
    }
    // 退回
    else if(type == '3') {
      return await useReturnWork(auditParams, formRef)
    }
    // 取回
    else if(type == '4') {
      return await useRetrieve(auditParams)
    }
  } catch (error) {}
}

// 格式化多人会签选择人员数据
const formatMutilForm = (key: string, data: object): object => {
  let tForm: {
    [key: string]: any
  } = {
    variables: {}
  }
  tForm.variables = { ...tForm.variables, ...data }
  if(key) {
    tForm.variables[key] = data['variables'] || []
    tForm.variables[key + '_byNum'] = (data['variables'] || []).length
  }
  return tForm
}